package com.yanqu.road.server.manger.activity;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eBigRankType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.rank.UserRank;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.bussiness.player.activity.GeneralActivityBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.helper.UnionHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.logic.rank.RankListModel;
import com.yanqu.road.logic.rank.UnionActivityRankListModel;
import com.yanqu.road.pb.crossunion.activity.CrossUnionActivityRankDataProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.cross.CrossDataMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.UnionActivityMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GeneralActivityRankMgr extends TempMgr {
    /**
     * activityId  type model
     */
    private static Map<Integer, Map<Integer, RankListModel>> rankListModelMap;
    /**
     * activityId  type model
     */
    private static Map<Integer, Map<Integer, UnionActivityRankListModel>> unionRankListModelMap;
    /**
     * activityId  type user conditionData
     */
    private static Map<Integer, Map<Integer, Map<Long, UserActivityConditionData>>> unionUserActivityDataMap;
    /**
     * activityId  type union conditionData
     */
    private static Map<Integer, Map<Integer, Map<String, UnionActivityConditionData>>> unionConditionDataMap;

    private static List<Integer> activityTypeList;


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (Map<Integer, Map<String, UnionActivityConditionData>> dataMap : unionConditionDataMap.values()) {
            for (Map<String, UnionActivityConditionData> unionActivityConditionDataMap : dataMap.values()) {
                for (UnionActivityConditionData data : unionActivityConditionDataMap.values()) {
                    if (data.isInsertOption()) {
                        UserActivityBussiness.addUnionActivityConditionData(data);
                    } else if (data.isUpdateOption()) {
                        UserActivityBussiness.updateUnionActivityConditionData(data);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean reloadData() {
        initActivityList();
        rankListModelMap = new ConcurrentHashMap<>();
        unionRankListModelMap = new ConcurrentHashMap<>();
        unionConditionDataMap = new ConcurrentHashMap<>();
        unionUserActivityDataMap = new ConcurrentHashMap<>();
        reloadRank();
        return true;
    }

    private void initActivityList() {
        activityTypeList = new ArrayList<>();
        activityTypeList.add(eActivityType.DaFuWeng.getValue());
        activityTypeList.add(eActivityType.BowArtActivity.getValue());
        activityTypeList.add(eActivityType.GhostActivity.getValue());
        activityTypeList.add(eActivityType.HangHaiActivity.getValue());
        activityTypeList.add(eActivityType.XiaowuRecallActivity.getValue());
        activityTypeList.add(eActivityType.DragonBoatRaceActivity.getValue());
        activityTypeList.add(eActivityType.WinterLoveActivity.getValue());
        activityTypeList.add(eActivityType.SeacraftActivity.getValue());
        activityTypeList.add(eActivityType.Tomb.getValue());
        activityTypeList.add(eActivityType.Twins.getValue());
        activityTypeList.add(eActivityType.CricketSeasonActivity.getValue());
        activityTypeList.add(eActivityType.PeakSeacraftActivity.getValue());
        activityTypeList.add(eActivityType.UnionRankActivity.getValue());
        activityTypeList.add(eActivityType.CrossRankActivity.getValue());
    }

    public static RankListModel getRankListModel(int activityId, int type) {
        if (rankListModelMap.containsKey(activityId)) {
            return rankListModelMap.get(activityId).get(type);
        }
        return null;
    }

    public static UnionActivityRankListModel getUnionRankListModel(int activityId, int type) {
        if (unionRankListModelMap.containsKey(activityId)) {
            return unionRankListModelMap.get(activityId).get(type);
        }
        return null;
    }

    /**
     * @param userId 是个人就行了
     */
    public static void removeUnionActivityRank(int activityId, int type, String unionUid, long userId) {
        GeneralActivityRankMgr.changeUnionActivityValue(activityId, type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_DELETE);
    }

    public static int getActivityRank(int activityId, int type, long userId) {
        RankListModel rankListModel = getRankListModel(activityId, type);
        if (null != rankListModel) {
            return rankListModel.getMyRank(userId);
        }
        return -1;
    }

    public static int getActivityUnionRank(int activityId, int type, String unionUid) {
        UnionActivityRankListModel rankListModel = getUnionRankListModel(activityId, type);
        if (null != rankListModel) {
            return rankListModel.getMyRank(unionUid);
        }
        return -1;
    }

    @Deprecated
    public static void changeRank(int activityId, int type, UserInfo userInfo, BigInteger value) {
        RankListModel rankListModel = getRankListModel(activityId, type);
        if (null != rankListModel) {
            UserRank userRank = rankListModel.rankChange(userInfo.getUserId(), UserMgr.parseUserBaseInfo(userInfo,
                    GameServer.getInstance().getServerId()), value, "");
            if (null != userRank) {//上传跨服
                //跨服活动排行变更，排名前100名上榜
                CrossDataMgr.generalActivityUserRankChange(activityId, type, userRank);
            }
        }
    }

    /**
     * 加载活动排行榜
     */
    public static void reloadRank() {
        List<ActivityInfo> activityInfoList = new ArrayList<>();
        for (int activityType : activityTypeList) {
            List<ActivityInfo> tempActivityList = NormalActivityMgr.getOpenActivityInfoList(activityType);
            activityInfoList.addAll(tempActivityList);
        }
        if (activityInfoList.isEmpty()) {
            return;
        }
        for (ActivityInfo activityInfo : activityInfoList) {
            //个人榜
            int activityId = activityInfo.getActivityId();
            int rankNum;
            if (!rankListModelMap.containsKey(activityInfo.getActivityId())) {
                rankListModelMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
            }
            List<Integer> conditionTypeList = NormalActivityMgr.getActivityConditionUserRankType(activityInfo.getActivityId());
            Map<Integer, RankListModel> userRankMap = rankListModelMap.get(activityInfo.getActivityId());
            for (Integer conditionType : conditionTypeList) {
                if (!userRankMap.containsKey(conditionType)) {
                    RankListModel rankListModel = new RankListModel(eBigRankType.Normal.getValue(), activityId);
                    rankNum = ActivityHelper.getMaxRank(NormalActivityMgr.getActivityConditionInfoMap(activityId).get(conditionType));
                    if (rankNum <= 0) {
                        rankNum = GameConfig.RANK_DEFAULT_MAX_COUNT;
                    }
                    rankListModel.setRankNum(rankNum);
                    rankListModel.setRankList(RankMgr.parseUserRankList(GeneralActivityBusiness.getUserActivityConditionDataList(
                            activityInfo.getActivityId(), conditionType, rankNum), rankNum));
                    userRankMap.put(conditionType, rankListModel);
                }
            }
            //商会榜
            if (!unionRankListModelMap.containsKey(activityInfo.getActivityId())) {
                unionRankListModelMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
                unionConditionDataMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
                unionUserActivityDataMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
            }
            List<Integer> unionConditionTypeList = NormalActivityMgr.getActivityConditionUnionRankType(activityInfo.getActivityId());
            Map<Integer, UnionActivityRankListModel> unionRankMap = unionRankListModelMap.get(activityInfo.getActivityId());
            for (Integer conditionType : unionConditionTypeList) {
                if (!unionRankMap.containsKey(conditionType)) {
                    Map<Long, UserActivityConditionData> tempUserConditionDataMap = GeneralActivityBusiness.getUserActivityRankConditionTypeDataMap(
                            activityInfo.getActivityId(), conditionType);
                    Map<String, UnionActivityConditionData> tempUnionConditionDataMap = UserActivityBussiness.getUnionActivityConditionDataMap(activityInfo.getActivityId(), conditionType);
                    UnionActivityMgr.checkUnionActivityConditionData(tempUserConditionDataMap, tempUnionConditionDataMap);
                    unionConditionDataMap.get(activityInfo.getActivityId()).put(conditionType, tempUnionConditionDataMap);
                    unionUserActivityDataMap.get(activityInfo.getActivityId()).put(conditionType, tempUserConditionDataMap);
                    UnionActivityRankListModel unionRankListModel = new UnionActivityRankListModel(activityInfo.getActivityId());
                    rankNum = ActivityHelper.getMaxRank(NormalActivityMgr.getActivityConditionInfoMap(activityId).get(conditionType));
                    if (rankNum <= 0) {
                        rankNum = GameConfig.RANK_DEFAULT_MAX_COUNT;
                    }
                    unionRankListModel.setRankNum(rankNum);
                    unionRankListModel.initRankList(tempUnionConditionDataMap);
                    unionRankMap.put(conditionType, unionRankListModel);
                }
            }
        }
    }

    public static void changeUnionActivityValue(int activityId, int type, String unionUid, long userId, UserActivityConditionData userConditionData, int notifyType) {
        ActivityInfo inTimeActivityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if (!ActivityMgr.activityInTime(inTimeActivityInfo)) {
            return;
        }
        //属于活动开始和结束时间
        /*    checkUnionConditionData(activityId, unionUid);
            UnionActivityConditionData unionActivityConditionData;
            synchronized (unionConditionDataMap) {
                unionActivityConditionData = getUnionActivityConditionData(activityId, unionUid, unionInfo, unionConditionDataMap, type);
                if (UnionRiseRankArgs.NOTIFY_TYPE_NORMAL == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_JOIN == notifyType) {
                    if (null != userConditionData) {
                        unionActivityConditionData.addMemberUserId(userConditionData.getUserId());
                        setUserActivityConditionData(userConditionData);
                        UnionActivityMgr.refreshUnionMemberPositionData(unionUid, unionActivityConditionData);
                    }
                } else if (UnionRiseRankArgs.NOTIFY_TYPE_REMOVE == notifyType) {
                    unionActivityConditionData.removeMemberUserId(userId);
                    UnionActivityMgr.refreshUnionMemberPositionData(unionUid, unionActivityConditionData);
                } else if (UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE == notifyType) {
                    UnionActivityMgr.refreshUnionMemberPositionData(unionUid, unionActivityConditionData);
                } else if (UnionRiseRankArgs.NOTIFY_TYPE_DELETE == notifyType) {
                    unionActivityConditionData.removeAllMemberUserId();
                    unionActivityConditionData.removeAllMemberPosition();
                }
                UnionActivityMgr.calcUnionActivityConditionValue(unionActivityConditionData, getUserActivityConditionDataMap(activityId, type));
            }
            UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(activityId, type);
            if (null != unionActivityRankListModel) {
                if (unionActivityConditionData.getMemberUserCount() > 0) {
                    UnionActivityRank unionRank = unionActivityRankListModel.rankChange(unionActivityConditionData);
                    if (null != unionRank) {
                        //CrossDataMgr.generalActivityUnionRankChange(activityId, type, unionRank, false);
                    }
                } else {
                    unionActivityRankListModel.removeRank(unionUid);
                    removeUnionActivityRank(activityId, type, unionUid);
                }
            }*/
        CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.Builder msg = CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.newBuilder();
        if (userConditionData == null) {
            msg.setUserId(0);
            msg.setValue("0");
        } else {
            msg.setUserId(userId);
            msg.setValue(userConditionData.getValue().toString());
        }
        msg.setActivityId(activityId);
        msg.setConditionType(type);
        msg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId())));
        msg.setUnionId(unionUid);
        msg.setChangeType(notifyType);
        Map<Long, Integer> positionMap = CrossUnionMgr.getMemberPositionMap(unionUid);
        for (Map.Entry<Long, Integer> entry : positionMap.entrySet()) {
            Long memberId = entry.getKey();
            Integer pos = entry.getValue();
            CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.Builder builder = CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.newBuilder();
            builder.setPos(pos);
            builder.setUserId(memberId);
            msg.addMember(builder);
        }
        msg.setUnionServerId(CrossUnionMgr.getUnionServerId(unionUid));
        UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionUid);
        if (unionBaseInfo != null) {
            msg.setUnionBaseInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
        }
        if (!CrossUnionMgr.isAllSync()) {
            return;
        }
        YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_ACTIVITY_USER_VALUE_CHANGE, msg);
        GamePlayerMgr.sendPacket(0, message);
    }

    private static UnionActivityConditionData getUnionActivityConditionData(int activityId, String unionUid, UnionInfo unionInfo, Map<Integer, Map<Integer, Map<String, UnionActivityConditionData>>> unionConditionDataMap, int type) {
        Map<Integer, Map<String, UnionActivityConditionData>> conditionMap = unionConditionDataMap.get(activityId);
        if (conditionMap == null) {
            conditionMap = new ConcurrentHashMap<>();
            unionConditionDataMap.put(activityId, conditionMap);
        }
        Map<String, UnionActivityConditionData> dataMap = conditionMap.get(type);
        if (dataMap == null) {
            dataMap = new ConcurrentHashMap<>();
            conditionMap.put(type, dataMap);
        }
        UnionActivityConditionData unionActivityConditionData = dataMap.get(unionUid);
        if (unionActivityConditionData == null) {
            unionActivityConditionData = new UnionActivityConditionData();
            unionActivityConditionData.setActivityId(activityId);
            unionActivityConditionData.setGetReward(false);
            unionActivityConditionData.setUnionUid(unionInfo.getUnionUid());
            unionActivityConditionData.setInfo("{}");
            unionActivityConditionData.setLastUpdateTime(System.currentTimeMillis() / 1000);
            unionActivityConditionData.setConditionType(type);
            Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
            if (unionMemberMap != null) {
                for (Long userId : unionMemberMap.keySet()) {
                    unionActivityConditionData.addMemberUserId(userId);
                }
                UnionActivityMgr.refreshUnionMemberPositionData(unionUid, unionActivityConditionData);
            }

            unionActivityConditionData.setInsertOption();
            dataMap.put(unionUid, unionActivityConditionData);
        }
        unionActivityConditionData.setUnionBaseInfo(UnionHelper.parseUnionBaseInfo(unionInfo, UserMgr.getUserInfo(unionInfo.getMasterUserId()), GameServer.getInstance().getServerId()));
        return unionActivityConditionData;
    }


    public static UnionActivityRankListModel getUnionActivityRankListModel(Integer activityId, int type) {
        if (unionRankListModelMap.containsKey(activityId)) {
            return unionRankListModelMap.get(activityId).get(type);
        }
        return null;
    }

    public static Map<Long, UserActivityConditionData> getUserActivityConditionDataMap(int activityId, int type) {
        if (unionUserActivityDataMap.containsKey(activityId)) {
            return unionUserActivityDataMap.get(activityId).get(type);
        }
        return null;
    }

    public static UserActivityConditionData getUserActivityConditionData(int activityId, int type, long userId) {
        Map<Long, UserActivityConditionData> dataMap = getUserActivityConditionDataMap(activityId, type);
        if (null != dataMap) {
            return dataMap.get(userId);
        }
        return null;
    }

    public static void setUserActivityConditionData(UserActivityConditionData userActivityConditionData) {
        if (null == userActivityConditionData) {
            return;
        }
        checkUnionUserConditionData(userActivityConditionData.getActivityId());
        Map<Long, UserActivityConditionData> dataMap = getUserActivityConditionDataMap(userActivityConditionData.getActivityId(), userActivityConditionData.getType());
        if (null != dataMap) {
            dataMap.put(userActivityConditionData.getUserId(), userActivityConditionData);
        }
    }

    public static UnionActivityConditionData getUnionActivityConditionData(int activityId, int type, String unionUid) {
        Map<String, UnionActivityConditionData> dataMap = getUnionActivityConditionDataMap(activityId, type);
        if (null != dataMap) {
            return dataMap.get(unionUid);
        }
        return null;
    }

    public static Map<String, UnionActivityConditionData> getUnionActivityConditionDataMap(int activityId, int type) {
        return unionConditionDataMap.get(activityId).get(type);
    }

    public static UnionActivityConditionData getUnionActivityConditionData(int activityId, int type, long userId) {
        Map<String, UnionActivityConditionData> dataMap = getUnionActivityConditionDataMap(activityId, type);
        if (null != dataMap) {
            for (UnionActivityConditionData unionActivityConditionData : dataMap.values()) {
                if (unionActivityConditionData.hasMemberUserId(userId)) {
                    return unionActivityConditionData;
                }
            }
        }
        return null;
    }

    private static void checkUnionUserConditionData(int activityId) {
        if (!unionUserActivityDataMap.containsKey(activityId)) {
            synchronized (unionUserActivityDataMap) {
                if (!unionUserActivityDataMap.containsKey(activityId)) {
                    unionUserActivityDataMap.put(activityId, new ConcurrentHashMap<>());
                }
            }
        }
    }

    private static void checkUnionConditionData(int activityId, String unionUid) {
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            if (!unionConditionDataMap.containsKey(activityId)) {
                synchronized (unionConditionDataMap) {
                    if (!unionConditionDataMap.containsKey(activityId)) {
                        unionConditionDataMap.put(activityId, new ConcurrentHashMap<>());
                    }
                }
            }
        }
    }
}
